package com.onegene.pdf.component.report.drug;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ReflectUtil;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.layout.Style;
import com.itextpdf.layout.borders.SolidBorder;
import com.itextpdf.layout.element.*;
import com.itextpdf.layout.layout.RootLayoutArea;
import com.itextpdf.layout.property.*;
import com.onegene.pdf.component.AbstractReportBuilder;
import com.onegene.pdf.component.Constant;
import com.onegene.pdf.component.IReportBuilder;
import com.onegene.pdf.component.entity.ReportBean;
import com.onegene.pdf.component.event.CatalogMoveEvent;
import com.onegene.pdf.component.event.DrugPageNumberEvent;
import com.onegene.pdf.component.event.HeaderTextEvent;
import com.onegene.pdf.component.factory.ReportBuilderContext;
import com.onegene.pdf.component.paint.CancerPainting;
import com.onegene.pdf.component.paint.DefaultPainting;
import com.onegene.pdf.component.report.CommonHandler;
import com.onegene.pdf.component.report.cancer.CancerComponent;
import com.onegene.pdf.component.report.cancer.CancerStyle;
import com.onegene.pdf.component.report.gene.GenoColor;
import com.onegene.pdf.component.report.gene.GenoComponent;
import com.onegene.pdf.component.report.gene.GenoReportBuilder;
import com.onegene.pdf.component.report.gene.GenoStyle;
import com.onegene.pdf.util.Precondition;
import lombok.extern.slf4j.Slf4j;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: laoliangliang
 * @description: 用药版本报告
 * @create: 2020/6/10 11:03
 **/
@Slf4j
public class DrugReportBuilder extends AbstractReportBuilder {
    private DrugPageNumberEvent drugPageNumberEvent;

    public DrugReportBuilder(ReportBuilderContext builderContext) {
        super(builderContext);
    }

    @Override
    public IReportBuilder addIndex() {
        doc.setCharacterSpacing(0.5f);
        Integer version = builderContext.getVersion();
        Image indexImage;
        if (version == 1) {
            indexImage = new Image(ImageDataFactory.create(DrugReportBuilder.class.getClassLoader().getResource("image/drug/resultCover.png")));
        } else {
            indexImage = new Image(ImageDataFactory.create(DrugReportBuilder.class.getClassLoader().getResource("image/drug/成人纸质报告-54.png")));
        }
        indexImage.setMargins(-50, -60, -60, -60);

        doc.add(indexImage);
        doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
        return this;
    }

    @Override
    public IReportBuilder addHello() {
        doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
        ReportBean.IndexBean index = reportBean.getIndex();

        DefaultPainting defaultPainting = new DefaultPainting(pdf, font);
        Integer version = builderContext.getVersion();
        if (version == 1) {
            defaultPainting.drawHello("image/drug/resultRemarks.png");
        } else {
            defaultPainting.drawHello("image/drug/hello.png");
        }
        defaultPainting.close();

        Div div = new Div();
        div.setWidth(UnitValue.createPercentValue(100));
        div.setHeight(UnitValue.createPercentValue(100));
        div.setHorizontalAlignment(HorizontalAlignment.CENTER);
        Paragraph p1 = new Paragraph();
        p1.setHorizontalAlignment(HorizontalAlignment.CENTER);
        p1.setMaxWidth(UnitValue.createPercentValue(80));
        p1.setMarginTop(80f);
        p1.setCharacterSpacing(0.4f);
        p1.setFontSize(10.5f);
        Style large = new Style();
        large.setFontSize(22);
        large.setFontColor(GenoColor.getThemeColor());
        if (version == 1) {
            p1.add(new Text("尊敬的" + index.getName() + ("FEMALE".equals(index.getGender()) ? "女士" : "MALE".equals(index.getGender()) ? "先生" : "") + "：\n").addStyle(large));
            p1.add(new Text("您好！\n"));
            p1.add(new Text("\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0衷心感谢您对我们的信任，选择用药安全基因检测服务!\n" +
                    "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0当您收到这份报告书的时候，我们已经根据您的需求，秉持科学、专业、严谨和保密的态度为您完成了本次基因检测，并根据您的个人特有基因检测结果进行了全面深入的分析。\n" +
                    "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0据统计，我国每年有5000万的住院病人，其中至少250万与药物不良反应有关，20多万人因此而死亡。我国住院病人中有20%是由于不合理用药造成的二次住院。而随着我国经济发展及老龄化趋势，我国三高等慢性病患者已超过3亿人，都面临着长期用药的危险。因此，临床用药安全已经成为我国一个重大难点和关注焦点。\n" +
                    "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0用药安全基因检测采用美国精准医疗先进理念，通过检测受检者基因信息，结合药物遗传学、药物基因组学等前沿科学研究成果，全面分析受检者对不同药物的代谢能力和敏感性，为受检者生病后的精准用药提供理论依据和实际指导。人体对药物的反应受到基因和环境等因素的共同影响，基因检测的最⼤意义在于挖掘受检者遗传信息中隐藏的用药风险，让受检者在日常用药过程中远离各种雷区，真正做到用对药、用准药。\n" +
                    "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0用药安全基因检测涵盖了大部分临床常⽤药物体系，综合打造⼀份只属于您个人的个性化用药建议，帮助您安全、高效击败各类疾病，享受健康生活。\n" +
                    "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0希望本次检测能为您带来舒适满意的体验，针对本次检测，如果您有任何疑问需要解答，敬请拨打我们的健康热线400-163-5588，我们恭候您的来电。\n" +
                    "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0壹基因衷心祝愿您身体健康，生活快乐！"));
        } else {
            p1.add(new Text("尊敬的" + index.getName() + "家长" + "：\n").addStyle(large));
            p1.add(new Text("您好！\n"));
            p1.add(new Text("\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0衷心感谢您对我们的信任，选择用药安全基因检测服务!\n" +
                    "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0当您收到这份报告书的时候，我们已经根据您的需求，秉承科学、专业、严谨和保密的态度为您的孩⼦完成了本次基因检测，并根据您孩⼦的个⼈特有基因检测结果进⾏了全⾯深⼊的分析。\n" +
                    "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0世界卫生组织（WHO）指出，全球有1/3的病人死于不合理用药，而非疾病本身。我国每年死于药物不良反应的人数高达19.2万人，而中有1/3都是儿童。因为儿童自身肝肾发育的不完善，使得药物不良反应发生率高达成人的2倍，新生儿更是达到成人的4倍。同时国内儿童专属的药物种类严重匮乏，儿科临床用药5成以上都是超说明书用药。因此，儿童临床的用药安全已经成为我国的一个重大难点和关注焦点。\n" +
                    "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0儿童用药安全基因检测采用美国精准医疗先进理念，通过检测孩⼦的基因信息，结合药物遗传学、药物基因组学等前沿科学研究成果，全面分析孩子对不同药物的代谢能力和敏感性，为孩子生病后的精准用药提供理论依据和实际指导。孩子对药物的反应受到基因和环境等因素的共同影响，基因检测的最大意义在于挖掘孩子遗传信息中隐藏的用药风险，让孩子在日常用药过程中远离各种雷区，真正做到用对药、用准药。\n" +
                    "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0⼉童用药安全基因检测一共涵盖了5大儿童常用药物体系，综合打造一份只属于您孩子个人的个性化用药建议，帮助孩子安全、高效击败各类疾病，健康茁壮成长。\n" +
                    "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0希望本次检测能为您带来舒适满意的体验，针对本次检测，如果您有任何疑问需要解答，敬请拨打我们的健康热线400-163-5588，我们恭候您的来电。\n" +
                    "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0壹基因衷⼼祝愿您的孩⼦健康成⻓、早⽇成才！ "));
        }
        div.add(p1);

        doc.add(div);
        return this;
    }

    @Override
    public IReportBuilder addExaminee() {
        ReportBean.IndexBean index = reportBean.getIndex();

        doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
        DefaultPainting defaultPainting = new DefaultPainting(pdf, font);
        Integer version = builderContext.getVersion();
        if (version == 1) {
            defaultPainting.drawHello("image/drug/person_result.png", -40);
        } else {
            defaultPainting.drawHello("image/drug/person.png", -40);
        }
        defaultPainting.close();

        Div div1 = new Div();
        div1.setMargins(100, 20, 0, 20);
        Paragraph p1 = new Paragraph();
        p1.add(new Paragraph("受检人信息").addStyle(GenoStyle.getSecondTitleStyle()));
        div1.add(p1);
        Paragraph p2 = new Paragraph();
        p2.add(new Text("姓名：" + index.getName() + "\n"));
        p2.add(new Text("性别： " + ("FEMALE".equals(index.getGender()) ? "女" : "MALE".equals(index.getGender()) ? "男" : "") + "\n"));
        p2.add(new Text("年龄：" + (DateUtil.year(new Date()) - index.getBirthYear()) + "\n"));
        p2.add(new Text("样本编号：" + index.getSampleCode() + "\n"));
        p2.add(new Text("检测项目：" + index.getPackageName() + "\n"));
        p2.add(new Text("样本检测结果：合格\n"));
        p2.add(new Text("报告日期：" + (DateUtil.format(new Date(), "yyyy年M月d日")) + "\n"));
        div1.add(p2);

        Paragraph p3 = new Paragraph();
        p3.setMarginTop(50);
        p3.add(new Text("用户须知\n").addStyle(GenoStyle.getSecondTitleStyle()));
        p3.add(new Text("1、检测位点的筛选基于国际权威数据库（pharmGKB）、世界权威组织发布的指南（CPIC、" +
                "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0DPWG）及顶级期刊杂志上发表的研究成果；\n" +
                "2、鉴于基因与表型关联的复杂性及科研⽔平局限性，本次检测⽆法覆盖与检测项⽬相关的所" +
                "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0有位点；\n" +
                "3、数据库将随着检测⼈数增加和科学研究的深⼊定期升级优化；\n" +
                "4、本报告是以药物基因组学的⻆度推测受检者对各种药物的可能反应，但临床⽤药所需考虑" +
                "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0的影响因素复杂，因此本报告不能作为临床⽤药的唯⼀依据；\n" +
                "5、由于药物的选择和调整需具备临床专业知识，所以家⻓切忌依据报告结果擅⾃调整⽤药，\n" +
                "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0需将结果⻛险反馈给专业的医⽣或药剂师，遵医嘱⽤药。"));
        div1.add(p3);
        doc.add(div1);
        return this;
    }

    @Override
    public IReportBuilder addDetectionContent() {
        Div div2 = new Div();
        div2.setMarginTop(30);
        div2.setPaddingRight(18);
        Table signatureTable = new Table(2);
        signatureTable.setHorizontalAlignment(HorizontalAlignment.RIGHT);
        signatureTable.setWidth(UnitValue.createPercentValue(50));
        signatureTable.addCell(GenoComponent.getSignCell().add(DrugComponent.getSignParagraph("检测人：舒平")));
        signatureTable.addCell(GenoComponent.getSignCell().add(DrugComponent.getSignParagraph("复核人：张萍")));
        signatureTable.startNewRow();
        signatureTable.addCell(GenoComponent.getSignCell().add(DrugComponent.getSignParagraph("日期：" + (DateUtil.format(new Date(), "yyyy年M月d日")))));
        signatureTable.addCell(GenoComponent.getSignCell().add(DrugComponent.getSignParagraph("日期：" + (DateUtil.format(new Date(), "yyyy年M月d日")))));
        div2.add(signatureTable);

        /*Image iconImage01 = new Image(ImageDataFactory.create(DrugReportBuilder.class.getClassLoader().getResource("image/gene/image-01.png")));
        iconImage01.setPaddingRight(18);
        iconImage01.setWidth(108);
        iconImage01.setHeight(108);
        iconImage01.setRelativePosition(292, 0, 60, 90);
        div2.add(iconImage01);*/
        doc.add(div2);

        RootLayoutArea layoutArea = (RootLayoutArea) doc.getRenderer().getCurrentArea();
        Rectangle bBox = layoutArea.getBBox();

        // 画印章
        CancerPainting cancerPainting = new CancerPainting(pdf, font);
        cancerPainting.drawStamper(bBox, builderContext);
        cancerPainting.close();
        return this;
    }

    @Override
    public IReportBuilder addResultSummary() {
        java.util.List<ReportBean.CategoriesBean> categories = reportBean.getCategories();
        ReportBean.IndexBean index = reportBean.getIndex();

        doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));

        drugPageNumberEvent = new DrugPageNumberEvent(doc, noPageSet);
        pdf.addEventHandler(PdfDocumentEvent.END_PAGE, drugPageNumberEvent);

        Paragraph header = GenoComponent.getHeaderLineText("检测结果概况");
        doc.add(header);

        Paragraph p1 = new Paragraph();
        p1.setFontSize(11);
        p1.add(new Text("检测结果概况\n").addStyle(GenoStyle.getTitleStyle().setFontSize(22f)));
        p1.add(new Text("本次检测包括"));
        int size = categories.size();
        int count = 0;
        StringBuilder categoryContent = new StringBuilder();
        for (int i = 0; i < size; i++) {
            ReportBean.CategoriesBean category = categories.get(i);
            if (category.getUnlockedItems() > 0) {
                categoryContent.append(category.getName()).append("、");
                count++;
            }
        }
        if (categoryContent.length() == 0) {
            log.error("没有解锁项：{}", reportBean.getIndex().getSampleCode());
        }
        p1.add(new Text(categoryContent.substring(0, categoryContent.length() - 1)).addStyle(GenoStyle.getThirdTitleStyle()));

        int avoidSize = index.getAvoidUseTags().size();
        int careSize = index.getCarefulUseTags().size();
        p1.add(new Text("等"));
        p1.add(new Text(count + "").addStyle(GenoStyle.getThirdTitleStyle()));
        p1.add(new Text("类共计"));
        p1.add(new Text(index.getUnlockedItems() + "").addStyle(GenoStyle.getThirdTitleStyle()));
        p1.add(new Text("种药物的用药安全情况，详情请参考详细检测结果； 其中"));
        p1.add(new Text((avoidSize > 0 ? avoidSize + "" : "")).addStyle(GenoStyle.getThirdTitleStyle()));
        p1.add(new Text((avoidSize > 0 ? "种药物需要避免使用，" : "暂无药物需要避免使用，")));
        p1.add(new Text((careSize > 0 ? careSize + "" : "")).addStyle(GenoStyle.getThirdTitleStyle()));
        p1.add(new Text((careSize > 0 ? "种药物需要谨慎使用，" : "暂无药物需要谨慎使用，")));
        p1.add(new Text("部分药物如下:\n"));
        doc.add(p1);

        Table t1 = new Table(2).useAllAvailableWidth();
        t1.setMargins(30, -20, 20, 0);
        Image goodTipImage = new Image(ImageDataFactory.create(GenoReportBuilder.class.getClassLoader().getResource("image/drug/icon/bm.png")));
        t1.addCell(GenoComponent.getDefaultCell(2, 1).setWidth(UnitValue.createPercentValue(20)).setPaddingBottom(30).add(goodTipImage.addStyle(GenoStyle.getLargeIconStyle())));
        t1.addCell(GenoComponent.getDefaultCell().setTextAlignment(TextAlignment.LEFT).add(new Paragraph("需避免使用的药物").addStyle(DrugStyle.getThirdTitleStyle())));
        // 优势标签
        java.util.List<ReportBean.IndexBean.TagBean> goodTags = index.getAvoidUseTags();
        int goodSize = goodTags.size();
        goodSize = goodSize > 16 ? 16 : goodSize;
        if (goodSize <= 0) {
            t1.addCell(GenoComponent.getDefaultCell().setTextAlignment(TextAlignment.LEFT).add(new Paragraph("暂无需要避免使用的药物").setMarginTop(-20)));
        } else {
            Div tabDiv = new Div();
            Paragraph element = new Paragraph();
            int len = 0;
            int offset = 0;
            for (int i = 0; i < goodSize; i++) {
                ReportBean.IndexBean.TagBean tagBean = goodTags.get(i);
                String label = tagBean.getName();
                len += label.length();
                Text text;
                if (len > 28) {
                    element.add(new Text("\n"));
                    text = new Text(label);
                    offset++;
                    len = 0;
                } else {
                    int i1 = (i - offset + 1) % 4;
                    if (i1 == 0) {
                        len = 0;
                    }
                    text = new Text(label + (i1 == 0 ? "\n" : ""));
                }
                Style style = new Style();
                style.setPaddings(3, 10, 3, 10);
                style.setBackgroundColor(DrugColor.getRedColor());
                style.setBorderRadius(new BorderRadius(8f, 11));
                style.setFontColor(ColorConstants.WHITE);
                style.setMargins(0, 3, 0, 3);
                text.addStyle(style);
                element.add(text);
            }
            tabDiv.add(element);
            t1.addCell(GenoComponent.getDefaultCell().add(tabDiv));
        }
        t1.startNewRow();

        // 需要注意
        Image badTipImage = new Image(ImageDataFactory.create(GenoReportBuilder.class.getClassLoader().getResource("image/drug/icon/js.png")));
        t1.addCell(GenoComponent.getDefaultCell(2, 1).setWidth(UnitValue.createPercentValue(20)).add(badTipImage.addStyle(GenoStyle.getLargeIconStyle())));
        t1.addCell(GenoComponent.getDefaultCell().setTextAlignment(TextAlignment.LEFT).add(new Paragraph("需谨慎使用的药物").addStyle(DrugStyle.getThreeTitleOrangeStyle())));


        java.util.List<ReportBean.IndexBean.TagBean> badTags = index.getCarefulUseTags();
        int badSize = badTags.size();
        badSize = badSize > 16 ? 16 : badSize;
        if (badSize == 0) {
            t1.addCell(GenoComponent.getDefaultCell().setTextAlignment(TextAlignment.LEFT).add(new Paragraph("暂无需要谨慎使用的药物").setMarginTop(-20)));
        } else {
            Div tabDiv = new Div();
            Paragraph element = new Paragraph();
            int len = 0;
            int offset = 0;
            for (int i = 0; i < badSize; i++) {
                ReportBean.IndexBean.TagBean tagBean = badTags.get(i);
                String label = tagBean.getName();
                len += label.length();
                Text text;
                if (len > 28) {
                    element.add(new Text("\n"));
                    text = new Text(label);
                    offset++;
                    len = 0;
                } else {
                    int i1 = (i - offset + 1) % 4;
                    if (i1 == 0) {
                        len = 0;
                    }
                    text = new Text(label + (i1 == 0 ? "\n" : ""));
                }
                Style style = new Style();
                style.setPaddings(3, 10, 3, 10);
                style.setBackgroundColor(DrugColor.getOrangeColor());
                style.setBorderRadius(new BorderRadius(8f, 11));
                style.setFontColor(ColorConstants.WHITE);
                style.setMargins(0, 3, 0, 3);
                text.addStyle(style);
                element.add(text);
            }
            tabDiv.add(element);
            t1.addCell(GenoComponent.getDefaultCell().add(tabDiv));
        }
        doc.add(t1);

        Div div = new Div();
        div.setFixedPosition(60, 90, UnitValue.createPercentValue(110));
        Paragraph p2 = new Paragraph();
//        p2.setFixedPosition(60, 90, UnitValue.createPercentValue(110));
        p2.add(GenoComponent.getSecondTitle("温馨提示"));
        div.add(p2);
        Image img1 = new Image(ImageDataFactory.create(GenoReportBuilder.class.getClassLoader().getResource("image/drug/icon/cg.png")));
        Image img2 = new Image(ImageDataFactory.create(GenoReportBuilder.class.getClassLoader().getResource("image/drug/icon/zq.png")));
        Image img3 = new Image(ImageDataFactory.create(GenoReportBuilder.class.getClassLoader().getResource("image/drug/icon/js1.png")));
        Image img4 = new Image(ImageDataFactory.create(GenoReportBuilder.class.getClassLoader().getResource("image/drug/icon/bm1.png")));
        Paragraph p3 = new Paragraph();
        p3.setFixedLeading(15);
        p3.setFontSize(10f);
        p3.add(img1.setHeight(8).setWidth(8).setMarginRight(2));
        p3.add(new Text("常规使用").setFontColor(DrugColor.getThemeColor()));
        p3.add(new Text("代表基因层面并无不适，可按临床常规方案用药；\n"));

        p3.add(img2.setHeight(8).setWidth(8).setMarginRight(2));
        p3.add(new Text("酌情使用").setFontColor(DrugColor.getYellowColor()));
        p3.add(new Text("代表在使用该药物时有可能出现药效问题或不良反应，需要进行监控并做出相应调整；\n"));

        p3.add(img3.setHeight(8).setWidth(8).setMarginRight(2));
        p3.add(new Text("谨慎使用").setFontColor(DrugColor.getOrangeColor()));
        p3.add(new Text("代表在使用该药物时需要通过调整用药剂量才能达到理想疗效或避免不良反应；\n"));

        p3.add(img4.setHeight(8).setWidth(8).setMarginRight(2));
        p3.add(new Text("避免使用").setFontColor(DrugColor.getRedColor()));
        p3.add(new Text("代表在使用该药物时会出现严重不良反应或无效，建议更换药物。\n"));
        div.add(p3);
        div.add(new Paragraph("※注意：结果建议仅从基因角度出发，此外还需考虑受检者的临床实际和过敏史，因此切勿私自调药，具体方案需咨询专业医生或药剂师。"));
        doc.add(div);

        DefaultPainting defaultPainting = new DefaultPainting(pdf, font);
        defaultPainting.drawHeader();
        defaultPainting.close();

        // 加个详细检测结果页
        doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
        noPageSet.add(pdf.getNumberOfPages());
        Image image88 = new Image(ImageDataFactory.create(GenoReportBuilder.class.getClassLoader().getResource("image/drug/详细检测结果.png")));
        image88.setMargins(-50, -60, -60, -60);
        doc.add(image88);
        return this;
    }

    @Override
    public IReportBuilder addContext() {
        List<String> cateArr = new ArrayList<>();
        cateArr.add("4");
        cateArr.add("3A");
        cateArr.add("3B");
        cateArr.add("3C");
        java.util.List<ReportBean.ItemsBean> gaoLevel = new LinkedList<>();
        java.util.Set<ReportBean.CategoriesBean> normalLecel = new LinkedHashSet<>();
        java.util.List<ReportBean.CategoriesBean> categories = reportBean.getCategories();
        for (ReportBean.CategoriesBean category : categories) {
            java.util.List<ReportBean.CategoriesBean.ItemsBean> items = category.getItems();
            for (ReportBean.CategoriesBean.ItemsBean item : items) {
                if (!item.getLocked()) {
                    ReportBean.ItemsBean itemsBean = reportBean.getItems().get(item.getCode());
                    if (cateArr.contains(item.getLevel())) {
                        gaoLevel.add(itemsBean);
                    } else {
                        normalLecel.add(category);
                    }
                }
            }
        }

        gaoLevel.sort((s1,s2)-> s2.getLevel() .compareTo(s1.getLevel()));
        // 高危项目
        for (ReportBean.ItemsBean itemsBean : gaoLevel) {
            ExtraParam extraParam = new ExtraParam(ExtraParam.CatalogType.ATTENTION);
            this.addBodyText(itemsBean, extraParam);
        }

        // 正常项目
        for (ReportBean.CategoriesBean categoriesBean : normalLecel) {
            int unlockedItems = categoriesBean.getUnlockedItems();
            if (unlockedItems == 0) {
                continue;
            }
            doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
            noPageSet.add(pdf.getNumberOfPages());
            URL resource = GenoReportBuilder.class.getClassLoader().getResource("image/drug/" + categoriesBean.getCode() + ".png");
            Precondition.checkNotNull(resource, "图片资源不存在：image/drug/" + categoriesBean.getCode() + ".png");
            Image backgroundImage = new Image(ImageDataFactory.create(resource));
            backgroundImage.setMargins(-50, -60, -60, -60);
            doc.add(backgroundImage);

            java.util.List<ReportBean.CategoriesBean.ItemsBean> items = categoriesBean.getItems();
            for (ReportBean.CategoriesBean.ItemsBean item : items) {
                ReportBean.ItemsBean itemsBean = reportBean.getItems().get(item.getCode());
                if (item.getLocked()) {
                    continue;
                }
                if ("1".equals(itemsBean.getLevel()) || "2A".equals(itemsBean.getLevel())
                        || "2B".equals(itemsBean.getLevel()) || "2C".equals(itemsBean.getLevel())) {
                    ExtraParam extraParam = new ExtraParam(ExtraParam.CatalogType.NORMAL);
                    this.addBodyText(itemsBean, extraParam);
                }
            }

        }
        return this;
    }

    /**
     * 添加主体文本
     *
     * @param itemsBean
     */
    private void addBodyText(ReportBean.ItemsBean itemsBean, ExtraParam extraParam) {
        String title = itemsBean.getCategoryName();

        HeaderTextEvent headerTextEvent = new HeaderTextEvent(title, font);
        pdf.addEventHandler(PdfDocumentEvent.START_PAGE, headerTextEvent);

        doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));

        // 获取当前目录
        CataLog cataLog = new CataLog(itemsBean.getIndex(), itemsBean.getCategoryName(), itemsBean.getName(), itemsBean.getLabel(), pdf.getNumberOfPages(), extraParam, itemsBean);
        java.util.List<CataLog> cataLogs = this.cataLogsMap.getOrDefault(extraParam.getType(), new ArrayList<>());
        cataLogs.add(cataLog);
        this.cataLogsMap.put(extraParam.getType(), cataLogs);

        // 检测结果正文
        Paragraph p1 = new Paragraph();

        p1.add(new Text(itemsBean.getName()).addStyle(DrugStyle.getTitleStyle()));
        p1.add(new Text(itemsBean.getEnName()).addStyle(DrugStyle.getSecondSmallTitleStyle()));
        doc.add(p1);

        Paragraph p2 = new Paragraph();
        p2.add(new Text("常用商品名:").setFontColor(DrugColor.getThemeColor()));
        String commonName = null;
        List<ReportBean.ItemsBean.ContentsBean> contents = itemsBean.getContents();
        for (ReportBean.ItemsBean.ContentsBean content : contents) {
            if ("常见名称".equals(content.getLabel())) {
                commonName = content.getValue().replaceAll("\\*", "、");
            }
        }
        Precondition.checkNotNull(commonName, "常见名称为空");
        p2.add(new Text("" + commonName));
        doc.add(p2);

        Paragraph p3 = new Paragraph();
        p3.add(GenoComponent.getSecondTitle("检测结果"));
        doc.add(p3);

        // 检测结果图标
        addDetectResult(itemsBean);

        // 用药建议
        addDrugSuggest(itemsBean);

        // 基因位点信息
        addGeneLocus(itemsBean);

        // 添加简介，不良反应，药物间相互影响，基因解读
        addContents(contents);

        // 文献
        addLiteratures(itemsBean);

        // 移除监听器
        pdf.removeEventHandler(PdfDocumentEvent.START_PAGE, headerTextEvent);
    }

    private void addLiteratures(ReportBean.ItemsBean itemsBean) {
        int number = 1;
        Div literatureDiv = new Div();
        Paragraph titleParagraph = GenoComponent.getTitleParagraph(new Text("参考文献（部分）").addStyle(GenoStyle.getSecondTitleStyle()));
        literatureDiv.add(titleParagraph);
        literatureDiv.setKeepTogether(true);
        for (ReportBean.ItemsBean.LiteraturesBean literature : itemsBean.getLiteratures()) {
            Paragraph segment = new Paragraph();
            segment.setFixedLeading(14);
            segment.setFontSize(9f).setFontColor(new DeviceRgb(85, 85, 85));
            segment.add(new Text("[" + (number++) + "]"));
            segment.add(new Text(literature.getAuthor() + ". "));
            segment.add(new Text(literature.getTitle() + ". "));
            segment.add(new Text(literature.getJournal() + ". "));
            segment.add(new Text(literature.getSerialNumber()));
            literatureDiv.add(segment);
        }
        doc.add(literatureDiv);
    }

    private void addContents(List<ReportBean.ItemsBean.ContentsBean> contents) {
        for (ReportBean.ItemsBean.ContentsBean content : contents) {
            if ("药物简介".equals(content.getLabel()) || "不良反应".equals(content.getLabel())
                    || "药物间相互影响".equals(content.getLabel()) || "基因解读".equals(content.getLabel())) {
                Div overall = new Div();
                overall.setKeepTogether(true);
                overall.add(new Paragraph(content.getLabel()).addStyle(CancerStyle.getThirdTitleStyle()).setMargin(0));
                java.util.List<IElement> iElements = getFixContent(content.getValue());
                handlerHtmlParagraph(overall, iElements);
                doc.add(overall);
            }
        }
    }

    private void addGeneLocus(ReportBean.ItemsBean itemsBean) {
        Div blockDiv = new Div();
        blockDiv.add(new Paragraph("基因位点信息").addStyle(CancerStyle.getThirdTitleStyle()));
        List<ReportBean.ItemsBean.GeneDescBean> geneDesc = itemsBean.getGeneDesc();
        Table geneLocusTable = new Table(5).useAllAvailableWidth();
        geneLocusTable.addCell(CancerComponent.getTableCell().setBorderRight(new SolidBorder(ColorConstants.WHITE, 1.08f)).addStyle(DrugStyle.getGeneDescCellHeadStyle()).add(new Paragraph("基因")).addStyle(CancerStyle.getTableHeader()));
        geneLocusTable.addCell(CancerComponent.getTableCell().setBorderRight(new SolidBorder(ColorConstants.WHITE, 1.08f)).addStyle(DrugStyle.getGeneDescCellHeadStyle()).add(new Paragraph("位点")).addStyle(CancerStyle.getTableHeader()));
        geneLocusTable.addCell(CancerComponent.getTableCell().setBorderRight(new SolidBorder(ColorConstants.WHITE, 1.08f)).addStyle(DrugStyle.getGeneDescCellHeadStyle()).add(new Paragraph("参考型")).addStyle(CancerStyle.getTableHeader()));
        geneLocusTable.addCell(CancerComponent.getTableCell().setBorderRight(new SolidBorder(ColorConstants.WHITE, 1.08f)).addStyle(DrugStyle.getGeneDescCellHeadStyle()).add(new Paragraph("检出型")).addStyle(CancerStyle.getTableHeader()));
        geneLocusTable.addCell(CancerComponent.getTableCell().addStyle(DrugStyle.getGeneDescCellHeadStyle()).add(new Paragraph("基因型解释")).addStyle(CancerStyle.getTableHeader()));
        if (geneDesc.size() > 16) {
            geneDesc = geneDesc.subList(0, 16);
        }
        for (ReportBean.ItemsBean.GeneDescBean geneDescBean : geneDesc) {
            geneLocusTable.startNewRow();
            geneLocusTable.addCell(CancerComponent.getTableCell().addStyle(DrugStyle.getGeneDescCellStyle()).add(new Paragraph(geneDescBean.getGene_code()).setFontColor(ColorConstants.BLACK)));
            geneLocusTable.addCell(CancerComponent.getTableCell().addStyle(DrugStyle.getGeneDescCellStyle()).add(new Paragraph(geneDescBean.getOg_id()).setFontColor(ColorConstants.BLACK)));
            geneLocusTable.addCell(CancerComponent.getTableCell().addStyle(DrugStyle.getGeneDescCellStyle()).add(new Paragraph(geneDescBean.getRef_genotype()).setFontColor(ColorConstants.BLACK)));
            geneLocusTable.addCell(CancerComponent.getTableCell().addStyle(DrugStyle.getGeneDescCellStyle()).add(new Paragraph(geneDescBean.getGenotype()).setFontColor(ColorConstants.BLACK)));
            geneLocusTable.addCell(CancerComponent.getTableCell().addStyle(DrugStyle.getGeneDescCellStyle()).add(new Paragraph(geneDescBean.getLabel()).setFontColor(ColorConstants.BLACK)));
        }
        blockDiv.add(geneLocusTable);
        doc.add(blockDiv);
    }

    private void addDetectResult(ReportBean.ItemsBean itemsBean) {
        Div resultDiv = new Div();
        Image icon = null;
        switch (itemsBean.getLabel()) {
            case "避免使用":
                icon = new Image(ImageDataFactory.create(DrugReportBuilder.class.getClassLoader().getResource("image/drug/icon/1.png")));
                break;
            case "谨慎使用":
                icon = new Image(ImageDataFactory.create(DrugReportBuilder.class.getClassLoader().getResource("image/drug/icon/2.png")));
                break;
            case "酌情使用":
                icon = new Image(ImageDataFactory.create(DrugReportBuilder.class.getClassLoader().getResource("image/drug/icon/3.png")));
                break;
            case "常规使用":
                icon = new Image(ImageDataFactory.create(DrugReportBuilder.class.getClassLoader().getResource("image/drug/icon/4.png")));
                break;
            default:
                break;
        }
        resultDiv.add(icon.setHorizontalAlignment(HorizontalAlignment.CENTER).setWidth(100).setHeight(35));
        resultDiv.add(new Paragraph("⚠警告：" + itemsBean.getSuitableAge()).setTextAlignment(TextAlignment.CENTER).setMarginTop(15).setFontSize(9));
        doc.add(resultDiv);
    }

    private void addDrugSuggest(ReportBean.ItemsBean itemsBean) {
        Paragraph p4 = new Paragraph();
        Image element = null;
        Text text = new Text("用药建议：");
        switch (itemsBean.getLabel()) {
            case "避免使用":
                element = new Image(ImageDataFactory.create(DrugReportBuilder.class.getClassLoader().getResource("image/drug/red.png")));
                text.setFontColor(DrugColor.getRedColor());
                break;
            case "谨慎使用":
                element = new Image(ImageDataFactory.create(DrugReportBuilder.class.getClassLoader().getResource("image/drug/orang.png")));
                text.setFontColor(DrugColor.getOrangeColor());
                break;
            case "酌情使用":
                element = new Image(ImageDataFactory.create(DrugReportBuilder.class.getClassLoader().getResource("image/drug/yellow.png")));
                text.setFontColor(DrugColor.getYellowColor());
                break;
            case "常规使用":
                element = new Image(ImageDataFactory.create(DrugReportBuilder.class.getClassLoader().getResource("image/drug/doc.png")));
                text.setFontColor(DrugColor.getThemeColor());
                break;
            default:
                break;
        }
        Precondition.checkNotNull(element, "label不合法");
        element.setHeight(17).setWidth(17);
        p4.add(element);
        p4.add(text);
        p4.add(new Text(itemsBean.getDescription()));
        p4.setFontSize(10.5f);
        doc.add(p4);
    }

    @Override
    public IReportBuilder addThanks() {
        doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
        pdf.removeEventHandler(PdfDocumentEvent.END_PAGE, drugPageNumberEvent);

//        properties.setProperty(Constant.FORBIDDE, pdf.getNumberOfPages() + "");

        DefaultPainting defaultPainting = new DefaultPainting(pdf, font);
        Integer version = builderContext.getVersion();
        if (version == 1) {
            defaultPainting.drawHello("image/drug/resultRemarks.png", -40);
        } else {
            defaultPainting.drawHello("image/drug/结束语.png", -40);
        }
        defaultPainting.close();
        Paragraph p1 = new Paragraph();
        p1.setHorizontalAlignment(HorizontalAlignment.CENTER);
        p1.setMaxWidth(UnitValue.createPercentValue(80));
        p1.setMarginTop(120f);
        p1.setFontSize(10.5f);
        p1.setCharacterSpacing(0.4f);
        p1.setFixedLeading(19);
        p1.setTextAlignment(TextAlignment.JUSTIFIED);
        p1.add(new Text("结束语:\n\n").setFontSize(12).setFontColor(DrugColor.getThemeColor()));
        if (version == 1) {
            p1.add(new Text("\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0再次感谢您选⽤壹基因提供的基因检测服务。“世界上没有两⽚同样的树叶。”对于⼈来说也是如此，由于基因的不同 导致了我们每个⼈对药物的吸收、代谢各有不同，因此由个体化用药为代表的 精准医疗已经成为了国际医学界公认的发展趋势。随着2016年中国版精准医疗计划的启动和实施，利用基因检测技术协助临床用药、精准打击的⽰例渐渐 出现在日常的电视新闻和报纸上，国内各大顶尖三甲医院也纷纷开设精准用药门诊，来响应国家政策。药物基因检测正在被越来越多的国人所接受。\n\n"));
            p1.add(new Text("\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0用药安全，是⼀项通过检测人体内药物代谢相关基因的多态性，来全⾯评估人体对各种药物反应个体化差异的服务。我们的检测结果可以在医生临床考量的基础上增加基因差异的维度，进⼀步排除个体用药时可能出现的多种雷区，帮助您高效选择适合自己的药物，远离日常用药的风险。\n\n"));
            p1.add(new Text("\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0基因检测是⼀个不断发展的新领域，目前壹基因还研发有针对疾病易感基因的相关检测项目，其中包括常见复杂疾病、营养吸收等⽅面，全部项目选取的基因 位点在⽬前已知的东亚特别是中国⼈群的研究比较明确，获得相关专业⽂献和数据库⽀持，但没有包括项目相关的所有基因位点。我们会持续跟踪人类基因 组研究的最新进展，并根据您的需要对检测报告进行更新，希望您能持续关注我们的服务。\n\n"));
            p1.add(new Text("\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0如果您对我们的检测服务和体验有任何意⻅或建议，敬请拨打我们的"));
            p1.add(new Text("健康热线400-163-5588").setFontColor(DrugColor.getThemeColor()));
            p1.add(new Text("，或者手机扫面下部二维码，联系您的专属健康顾问。"));
        } else {
            p1.add(new Text("\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0再次感谢您选⽤壹基因提供的基因检测服务。\n\n"));
            p1.add(new Text("\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0“世界上没有两片同样的树叶。”对于人来说也是如此，由于基因的不同导致了我们每个人对药物的吸收、代谢各有不同，因此由个体化用药为代表的精准医疗已经成为了国际医学界公认的发展趋势。随着2016年中国版精准医疗计划的启动和实施，利用基因检测技术协助临床用药、精准打击的示例渐渐出现在日常的电视新闻和报纸上，国内各大顶尖三甲医院也纷纷开设精准用药门诊，来响应国家政策。药物基因检测正在被越来越多的国人所接受。\n\n"));
            p1.add(new Text("\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0儿童用药安全，是⼀项通过检测⼉童体内药物代谢相关基因的多态性，来全面评估孩子对各种药物反应个体化差异的服务。我们的检测结果可以在医生临床考量的基础上增加基因差异的维度，进一步排除个体用药时可能出现的多种雷区，帮助孩子高效选择适合自己的药物，远离日常用药的风险。\n\n"));
            p1.add(new Text("\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0基因检测是⼀个不断发展的新领域，⽬前壹基因还研发有针对成年⼈的相关检测项⽬，其中包括常⻅复杂疾病、营养吸收等⽅⾯，全部项⽬选取的基因位点在⽬前已知的东亚特别是中国⼈群的研究⽐较明确，获得相关专业⽂献和数据库⽀持，但没有包括项⽬相关的所有基因位点。我们会持续跟踪⼈类基因组研究的最新进展，并根据您的需要对检测报告进⾏更新，希望您能持续关注我们的服务。\n\n"));
            p1.add(new Text("\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0如果您对我们的检测服务和体验有任何意⻅或建议，敬请拨打我们的"));
            p1.add(new Text("健康热线400-163-5588").setFontColor(DrugColor.getThemeColor()));
            p1.add(new Text("，或者手机扫面下部二维码，联系您的专属健康顾问。"));
        }

        doc.add(p1);


//        URL resource = GenoReportBuilder.class.getClassLoader().getResource("image/drug/resultRemarks.png");
//        Image backImage = new Image(ImageDataFactory.create(resource));
//        int pageNum = pdf.getNumberOfPages();
//        backImage.setFixedPosition(pageNum, 0, 0, UnitValue.createPercentValue(125));
//        backImage.scale(1, 1.05f);
//        doc.add(backImage);

        try {
            Image csQrCodeImage = new Image(ImageDataFactory.create(reportBean.getIndex().getCsQrCode()));
            csQrCodeImage.setMarginTop(5);
            csQrCodeImage.setHorizontalAlignment(HorizontalAlignment.CENTER);
            csQrCodeImage.setWidth(90);
            csQrCodeImage.setHeight(90);
            doc.add(csQrCodeImage);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return this;
    }

    @Override
    public IReportBuilder addBackCover() {
        Image honorImage = new Image(ImageDataFactory.create(GenoReportBuilder.class.getClassLoader().getResource("image/drug/honor.png")));
        honorImage.setMargins(-50, -60, -60, -60);
        doc.add(honorImage);

        doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
        doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));

        Image backCoverImage;
        Integer version = builderContext.getVersion();
        if (version == 1) {
            backCoverImage = new Image(ImageDataFactory.create(GenoReportBuilder.class.getClassLoader().getResource("image/drug/resultBack.png")));
        } else {
            backCoverImage = new Image(ImageDataFactory.create(GenoReportBuilder.class.getClassLoader().getResource("image/drug/封底-02.png")));
        }
        backCoverImage.setWidth(UnitValue.createPercentValue(100));
        backCoverImage.scale(1.3f, 1.3f);
        backCoverImage.setMarginLeft(-70);
        backCoverImage.setMarginTop(-80);
        doc.add(backCoverImage);
        return this;
    }

    @Override
    public IReportBuilder addCatalog() {
        CatalogMoveEvent catalogMoveEvent = new CatalogMoveEvent(properties);
        pdf.addEventHandler(PdfDocumentEvent.END_PAGE, catalogMoveEvent);
        doc.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
        // 目录
        Div div1 = getCataLogDiv(0);
        doc.add(div1);
        pdf.removeEventHandler(PdfDocumentEvent.END_PAGE, catalogMoveEvent);

        int startPage = 5;
        int numberOfPages = pdf.getNumberOfPages();
        Integer catalogSize = Integer.parseInt(properties.getProperty(Constant.CATALOG_SIZE));
        List<PdfPage> pagesMove = catalogMoveEvent.getPagesMove();
        if (catalogSize > 1) {
            PdfPage pdfPage1 = pagesMove.get(pagesMove.size() - 1);
            TreeMap map = (TreeMap) ReflectUtil.getFieldValue(pdfPage1.getPdfObject(), "map");
            for (PdfPage pdfPage : pagesMove) {
                ReflectUtil.setFieldValue(pdfPage.getPdfObject(), "map", map);
            }
        }
        for (int i = 0; i < catalogSize; i++) {
            pdf.movePage(numberOfPages, startPage);
        }
        doc.flush();
        return this;
    }

    @Override
    public IReportBuilder addPageNumber() {
        return null;
    }


    private Div getCataLogDiv(int offPage) {
        Image catalogImageHeader = new Image(ImageDataFactory.create(GenoReportBuilder.class.getClassLoader().getResource("image/drug/目录2.png")));
        catalogImageHeader.scale(0.4f, 0.4f);
        catalogImageHeader.setMarginBottom(30);
        doc.add(catalogImageHeader);

        float firstCol = 50f;
        java.util.List<CataLog> cataLogsAttention = cataLogsMap.getOrDefault(ExtraParam.CatalogType.ATTENTION, new LinkedList<>());
        java.util.List<CataLog> cataLogsNormal = cataLogsMap.getOrDefault(ExtraParam.CatalogType.NORMAL, new LinkedList<>());
        Div div1 = new Div();
        Table tableCatalog = new Table(4).useAllAvailableWidth();
        tableCatalog.addCell(GenoComponent.getCatelogCell().setWidth(UnitValue.createPercentValue(firstCol)).add(new Paragraph("检测结果概况")));
        Cell catelogCell = GenoComponent.getCatelogCell(2);
        tableCatalog.addCell(catelogCell.add(GenoComponent.getCatelogDottedLine(2)));
        tableCatalog.addCell(GenoComponent.getCatelogCell().add(new Paragraph("1")));
        tableCatalog.startNewRow();
        String tailAttention = cataLogsAttention.size() == 0 ? "（无）" : "";
        // 需要注意 动态变化
        tableCatalog.addCell(GenoComponent.getCatelogCell().setWidth(UnitValue.createPercentValue(firstCol)).add(new Paragraph("需要注意" + tailAttention).addStyle(GenoStyle.getSecondTitleStyle())));
        tableCatalog.startNewRow();

        //添加具体目录明细
        this.addCatalogDetail(offPage, tableCatalog, cataLogsAttention);

        String tailNormal = cataLogsNormal.size() == 0 ? "（无）" : "";

        // 正常项目 动态变化
        tableCatalog.addCell(GenoComponent.getCatelogCell().setWidth(UnitValue.createPercentValue(firstCol)).add(new Paragraph("正常项目" + tailNormal).addStyle(GenoStyle.getSecondTitleStyle())));
        tableCatalog.startNewRow();
        Map<String, java.util.List<CataLog>> cataLogMap = cataLogsNormal.stream().collect(Collectors.groupingBy(CataLog::getCategoryName, LinkedHashMap::new, Collectors.toList()));
        Set<Map.Entry<String, java.util.List<CataLog>>> entries1 = cataLogMap.entrySet();
        for (Map.Entry<String, java.util.List<CataLog>> cataLogEntry : entries1) {
            String categoryName = cataLogEntry.getKey();
            tableCatalog.addCell(GenoComponent.getCatelogCell().setWidth(UnitValue.createPercentValue(firstCol)).add(new Paragraph(categoryName).addStyle(GenoStyle.getSecondTitleStyle().setFontSize(12))));
            tableCatalog.startNewRow();
            java.util.List<CataLog> values = cataLogEntry.getValue();

            //添加具体目录明细
            this.addCatalogDetail(offPage, tableCatalog, values);
        }
        tableCatalog.addCell(GenoComponent.getCatelogCell().setWidth(UnitValue.createPercentValue(firstCol)).add(new Paragraph("结束语").addStyle(GenoStyle.getSecondTitleStyle())));
        div1.add(tableCatalog);
        return div1;
    }

    private void addCatalogDetail(int offPage, Table tableCatalog, java.util.List<CataLog> values) {
        for (CataLog cataLog : values) {
            Paragraph element = new Paragraph();
            element.add(new Text(cataLog.getName()));
            List<ReportBean.ItemsBean.ContentsBean> contents = cataLog.getItemsBean().getContents();
            StringBuilder sb = new StringBuilder();
            sb.append("(");
            for (ReportBean.ItemsBean.ContentsBean content : contents) {
                if ("主要适应症".equals(content.getLabel()) || "主要适用症".equals(content.getLabel())) {
                    sb.append(content.getValue().replaceAll("\\*", "、"));
                }
            }
            sb.append(")");
            element.add(new Text(sb.toString()).setFontColor(DrugColor.getThemeColor()));
            element.setFontSize(10.5f);
            tableCatalog.addCell(GenoComponent.getCatelogCell().add(element));
            tableCatalog.addCell(GenoComponent.getCatelogCell().add(GenoComponent.getCatelogDottedLine(4)));
            tableCatalog.addCell(GenoComponent.getCatelogCell().add(new com.itextpdf.layout.element.List().setFontSize(10.5f).add(new ListItem(cataLog.getLabel())
                    .setListSymbol(new Image(ImageDataFactory.create(GenoReportBuilder.class.getClassLoader().getResource("image/gene/" + selectColor(cataLog) + "-point.png")))
                            .addStyle(GenoStyle.getDefaultPoint())))));
            tableCatalog.addCell(GenoComponent.getCatelogCell().add(new Paragraph((cataLog.getPageNumber() - 4) + "").setFontSize(10.5f)));
            tableCatalog.startNewRow();
        }
    }

    private String selectColor(CataLog cataLog) {
        switch (cataLog.getItemsBean().getLevel()) {
            case "1":
                return "blue";
            case "2A":
            case "2B":
            case "2C":
                return "orange";
            case "3A":
            case "3B":
            case "3C":
                return "or";
            case "4":
                return "red";
            default:
                break;
        }
        return "blue";
    }

    private java.util.List<IElement> getFixContent(String content) {
        content = content.replaceAll("<p(.*?)>", "<div>");
        content = content.replaceAll("</p>", "</div>");
        if (content.startsWith("<div>")) {
            content = content.replaceAll("<div>", "<div style='line-height:18pt;font-size:16px;'>");
        } else {
            content = "<div style='line-height:18pt;font-size:16px;'>" + content + "</div>";
        }
        content = content.replaceAll("<b>", "<span>");
        content = content.replaceAll("</b>", "</span>");
        return HtmlConverter.convertToElements(content, proper);
    }

    /**
     * 通过itext7转换html文本成元素组件后取出文本，自行组装成段落（Paragraph）
     * 优点：此方法优势在于可以大量减小PDF体积，数据越多可大约减少三分之二的大小
     * 缺点：目前只支持字体颜色及粗体两种html样式，后续若需要添加需要修改代码
     */
    private void handlerHtmlParagraph(Div overall, java.util.List<IElement> iElements) {
        Style style = new Style();
        style.setFontSize(10);
        style.setTextAlignment(TextAlignment.JUSTIFIED);
        style.setCharacterSpacing(0.7f);
        style.setMarginTop(0);
        style.setMarginBottom(0);
        Paragraph paragraph = new Paragraph().addStyle(style);
        paragraph.setFixedLeading(18f);
        for (IElement iElement : iElements) {
            CommonHandler.handlerElement(iElement, paragraph);
        }
        overall.add(paragraph);
    }
}
